package model

import (
	"fmt"
	"github.com/go-xorm/xorm"
	"global/structs"
	"time"
)

const (
	Status_Wait = iota
	Status_Partially
	Status_All
	Status_Revoke

	IsNew_Yes = "1"
	IsNew_No  = "0"
)

type trustCoinModel struct{}

var TrustCoinModel = new(trustCoinModel)

// 将委托单状态修改为 OLD
func (trustCoinModel) UpdateIsNew(tid int, status string) (bool, error) {
	item := new(structs.TrustCoin)
	item.IsNew = status
	item.UpdateTime = time.Now()
	rows, err := MainDB.Where("id=?", tid).Cols("is_new", "update_time").Update(item)
	if err != nil {
		return false, err
	}
	if rows > 0 {
		return true, nil
	}
	return false, fmt.Errorf("no row affected, tid: %d", tid)
}

func (trustCoinModel) Cancel(sess *xorm.Session, tid int) (bool, error) {
	item := new(structs.TrustCoin)
	item.Status = int(Status_Revoke)
	item.UpdateTime = time.Now()
	rows, err := sess.Where("id=?", tid).Cols("status", "update_time").Update(item)
	if rows > 0 {
		return true, nil
	}
	return false, err
}

func (trustCoinModel) UpdateWithoutSession(coin *structs.TrustCoin) (bool, error) {
	coin.UpdateTime = time.Now()
	affected, err := MainDB.Where("id=?", coin.Id).
		Cols("number_available", "number_deal", "is_new", "status", "update_time").
		Update(coin)
	if affected > 0 {
		return true, nil
	}
	return false, err
}

// 更新委托单表
func (trustCoinModel) Update(session *xorm.Session, id int, coin *structs.TrustCoin) (bool, error) {
	coin.UpdateTime = time.Now()
	affected, err := session.Where("id=?", id).
		Cols("number_available", "number_deal", "is_new", "status", "update_time").
		Update(coin)
	if affected > 0 {
		return true, nil
	}
	return false, err
}

// 获取一条数据
func (trustCoinModel) Get(id int) (*structs.TrustCoin, error) {
	item := new(structs.TrustCoin)
	_, err := MainDB.Where("id=?", id).Get(item)
	return item, err
}
